/**Eureka+Ribbon+spring-cloud-gateway:是客户端调用服务的入口，主要功能是将不同的请求转发至不同的处理微服务模块，通常要集成负载均衡服和熔断，
 * 1）依赖库：SpringCloud版本为Hoxton及以下，核心依赖为spring-cloud-starter-netflix-eureka-client（含ribbon和spring-cloud-starter-gateway
 * 2）main上@EnableDiscoveryClient
 * 3）在YAML或main文件中定义负载均衡策略和相关属性
 * 4）在YAML或main文件中定义路由及其predicate、filter
 */
package com.example.demogatewayribbon;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

@SpringBootApplication
@EnableDiscoveryClient
public class DemoGatewayRibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoGatewayRibbonApplication.class, args);
    }

    //路由断言
    @Bean
    public RouterFunction<ServerResponse> testRouterFunction() {
        RouterFunction<ServerResponse> route = RouterFunctions.route(
                RequestPredicates.path("/test"), request -> ServerResponse.ok()
                        .body(BodyInserters.fromProducer("I am testing",String.class)));
        return route;
    }

    //路由过滤器
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("path_route", r -> r.path("/def")
                        .filters(f -> f.stripPrefix(1))
                        .uri("https://www.baidu.com"))
                .build();
    }

//    @Bean
//    public IRule ribbonRule() {
//        return new RandomRule();
//    }
}
